<?php
/**
 * 文本 日志  
 *
 * @filesource _filelog.class.php
 * @package peck
 * @subpackage _log
 * @version $id: 0.1, utf8, $
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2010 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example 
 *   
 */
class _filelog {

    /**
     * 优先级
     */
    const EMERG   = 'EMERG';   // Emergency: system is unusable
    const ALERT   = 'ALERT';   // Alert: action must be taken immediately
    const CRIT    = 'CRIT';    // Critical: critical conditions
    const ERR     = 'ERR';     // Error: error conditions
    const WARN    = 'WARN';    // Warning: warning conditions
    const NOTICE  = 'NOTICE';  // Notice: normal but significant condition
    const INFO    = 'INFO';    // Informational: informational messages
    const DEBUG   = 'DEBUG';   // Debug: debug messages

    /**
     * 文件全路径
     *
     * @param string $_filename
     */
    protected $_filename;

    /**
     * 日期格式
     *
     * @var string
     */
    protected $_date_format = 'Y-m-d H:i:s';

    private function __construct(){}
    private function __clone(){}

    //单间模式
    public static function object($logfile=null){
        $logfile = empty($logfile) ? 'default' : $logfile;
        $key = 'log:'.$logfile;
        $oo = '__objects';

        if( isset($GLOBALS[$oo][$key]) ){
            if($GLOBALS[$oo][$key] instanceof self){
                return $GLOBALS[$oo][$key];
            }
        }

        $object = new self();
        $policy = !empty($GLOBALS['__configs']['log'])
            ? $GLOBALS['__configs']['log']
            : null;
        $policy['log_dir'] = !empty($policy['log_dir'])
            ? realpath($policy['log_dir']) 
            : '/tmp';
        $policy['log_format'] = !empty($policy['log_format']) 
            ? $policy['log_format']
            : 'ymd';

        $object->_filename = $policy['log_dir'].DIRECTORY_SEPARATOR.$logfile.'-'.date($policy['log_format']).'.log';
        
        $GLOBALS[$oo][$key] = $object;
        return $GLOBALS[$oo][$key];
    }

    /**
     * 记录日志
     *
     * @param string $text
     * @return boolean
     */
    public function log($text, $priority=null){
        if( in_array(gettype($text), array('array', 'object', 'resource',))){
            throw new LogicException('('.__METHOD__.')'.'Error: text is not string!');
            return false;
        }

        $priority = empty($priority) ? self::INFO : $priority;
        $text = date($this->_date_format)." {$priority}: {$text}\n";
        return error_log($text, 3, $this->_filename);
    }

}


